package codingforgreat.lchot150;

import java.util.LinkedHashMap;

public class Lc146 {
    class LRUCache {
        public LinkedHashMap<Integer,Integer> LRU;
        public int capacity;

        public LRUCache(int capacity) {
            this.capacity = capacity;
            LRU = new LinkedHashMap<>(capacity);

        }

        public int get(int key) {
            if (!LRU.containsKey(key)) {
                return -1;
            }
            // 将 key 变为最近使用
            int val =  LRU.get(key);
            LRU.remove(key);
            LRU.put(key,val);
            return val;
        }

        public void put(int key, int value) {
            if(LRU.containsKey(key)){
                LRU.remove(key);
            }
            if (LRU.size() >= this.capacity) {
                // 链表头部就是最久未使用的 key
                int oldestKey = LRU.keySet().iterator().next();
                LRU.remove(oldestKey);
            }
            LRU.put(key,value);
        }
    }

}
